package hhh.data.net;

import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import hhh.data.Code;
import hhh.data.bean.User;
import hhh.data.rxjava.RxResultHelper;
import hhh.data.rxjava.SchedulersCompat;
import io.reactivex.Observable;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/6/30 0030.
 */
public class RetrofitFactory {
    private static OkHttpClient httpClient=new OkHttpClient().newBuilder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder=chain.request().newBuilder();
                    builder.addHeader("token","123");
                    return chain.proceed(builder.build());
                }
            })
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {

                }
            }).setLevel(HttpLoggingInterceptor.Level.BASIC))
            .connectTimeout(Code.TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(Code.TIMEOUT,TimeUnit.SECONDS)
            .build();

    private static Api apiService=new Retrofit.Builder()
            .baseUrl(Code.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(Api.class);

    public Observable<User> login(String user, String password){
        return apiService.login(user,password)
                .compose(RxResultHelper.<User>handleResult())
                .compose(SchedulersCompat.<User>io_main());
    }
}
